﻿using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Models;
using Magicodes.ExporterAndImporter.Excel;
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuddHa.Common.FileExportOpex
{
    public class ExcelExportHelper
    {
        public IExcelExporter _excelExporter = new ExcelExporter();
        public IExcelImporter _excelImporter = new ExcelImporter();

        public async Task<FileContentResult> ExportExcel<T>(List<T> lists, string fileDownloadName) where T : class, new()
        {
            var excelByte = await _excelExporter.ExportHeaderAsByteArray(new T());
            if (lists != null || lists.Count() > 0)
            {
                await _excelExporter.ExportAsByteArray(lists);
            }
            else
            {
                throw new ArgumentNullException("lists is null");
            }
            excelByte = await _excelExporter.ExportAsByteArray(lists);
            return ExportFileContentResult(excelByte, fileDownloadName);
        }

        public async Task<ExportFileInfo> ExportExcelInFile<T>(List<T> lists, string fileDownloadName) where T : class, new()
        {
            var result = await _excelExporter.Export(fileDownloadName,
            lists);
            return result;
        }

        public async Task<ImportResult<T>> ImportExcel<T>(HttpRequest httpRequest) where T : class, new()
        {
            if (httpRequest.Form.Files.Count < 1)
            {
                throw new Exception("文件不存在");
            }
            var formFile = httpRequest.Form.Files[0];
            var importFile = await _excelImporter.Import<T>(formFile.OpenReadStream());
            return importFile;
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="fileContents"></param>
        /// <param name="FileDownloadName"></param>
        /// <returns></returns>
        public static FileContentResult ExportFileContentResult(byte[] fileContents, string FileDownloadName)
        {
            var fileContentResult = new FileContentResult(fileContents, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = FileDownloadName + ".xlsx"
            };
            return fileContentResult;
        }
    }
}
